﻿using M.Warehouse.API.Application.Command.WarehousesCommand;
using M.Warehouse.Domain;
using M.Warehouse.Domain.DTO;
using M.Warehouse.Repository.WarehouseInterface;
using MediatR;

namespace M.Warehouse.API.Application.CommandHandlers.WarehousesHandlers
{
    /// <summary>
    /// 显示仓库中介者
    /// </summary>
    public class WarehousesShowCommandHandlers : IRequestHandler<WarehousesShowCommand, PageDTO<Warehouses>>
    {
        /// <summary>
        /// 仓库仓储接口
        /// </summary>
        private readonly IWarehouseWRepository _warehouseWRepository;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="warehouseWRepository"></param>
        public WarehousesShowCommandHandlers(IWarehouseWRepository warehouseWRepository)
        {
            _warehouseWRepository = warehouseWRepository;
        }
        /// <summary>
        /// 显示仓库
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageDTO<Warehouses>> Handle(WarehousesShowCommand request, CancellationToken cancellationToken)
        {
            var list = (await _warehouseWRepository.GetAllAsync()).Where(x => !x.IsDeleted);
            if (!string.IsNullOrEmpty(request.WarehouseNo))
            {
                list=list.Where(x=>x.WarehouseNo.Contains(request.WarehouseNo));
            }
            if (!string.IsNullOrEmpty(request.LocationCoding))
            {
                list = list.Where(x => x.LocationCoding.Contains(request.LocationCoding));
            }
            if (request.WarehouseState != null)
            {
                list = list.Where(x => x.WarehouseState == request.WarehouseState);
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = list.Count();
            }
            PageDTO<Warehouses> page = new PageDTO<Warehouses>();
            page.TotalCount= list.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list=list.OrderByDescending(x=>x.CreatedDate).Skip((int)(request.PageIndex-1)*(int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
